<!--
 * @Descripttion: 销售管理，工序回报单
 * @version: V1.0
 * @Author: GaoWei
 * @Date: 2021-05-11 18:54:11
 * @LastEditors: GW
 * @LastEditTime: 2021-09-27 17:32:27
-->
<template>
    <div class="content-wrapper a-base-container">
        <div class="requisition-set-wrapper">
            <!-- 按钮 -->
            <div class="btn-wrapper clearfix">
                <a-row class="text-center clearfix">
                    <a-col :xs="24" :sm="24" :md="24" :lg="16" :xl="12">
                        <a-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2" v-if="permissions.includes('productionProcessReport:add')">
                            <div class="btns" style="display:block;margin-left:10px">
                                <a class="ant-dropdown-link" @click="showModelsClick">
                                    <a-icon class="btns-icon" type="file-add" />
                                    <div class="btns-text">新增</div>
                                </a>
                            </div>
                        </a-col>
                        <a-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2" :class="[xgType?'btns-disable':'']" v-if="permissions.includes('productionProcessReport:edit')">
                            <div class="btns" style="display:block;margin-left:10px">
                                <a class="ant-dropdown-link" @click="deleteClick(1)">
                                    <a-icon class="btns-icon" type="edit" />
                                    <div class="btns-text">修改</div>
                                </a>
                            </div>
                        </a-col>
                        <a-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2" :class="[scType?'btns-disable':'']" v-if="permissions.includes('productionProcessReport:delete')">
                            <div class="btns" style="display:block;margin-left:10px">
                                <a class="ant-dropdown-link" @click="deleteClick(2)">
                                    <a-icon class="btns-icon" type="delete" />
                                    <div class="btns-text">删除</div>
                                </a>
                            </div>
                        </a-col>

                        <a-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2" :class="[shType?'btns-disable':'']" v-if="permissions.includes('productionProcessReport:examine')">
                            <div class="btns" style="display:block;margin-left:10px">
                                <a class="ant-dropdown-link" @click="shClick(1)">
                                    <a-icon class="btns-icon" type="audit" />
                                    <div class="btns-text">审核</div>
                                </a>
                            </div>
                        </a-col>
                        <a-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2" :class="[qsType?'btns-disable':'']" v-if="permissions.includes('productionProcessReport:examine')">
                            <div class="btns" style="display:block;margin-left:10px">
                                <a class="ant-dropdown-link" @click="shClick(2)">
                                    <a-icon class="btns-icon" type="audit" />
                                    <div class="btns-text">弃审</div>
                                </a>
                            </div>
                        </a-col>
                        <a-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2" v-if="permissions.includes('productionProcessReport:export')">
                            <div class="btns" style="display:block;margin-left:10px">
                                <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                                    <a-icon class="btns-icon" type="export" />
                                    <div class="btns-text">导出</div>
                                </a>
                            </div>
                        </a-col>
                        <a-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2" v-if="permissions.includes('productionProcessReport:export')">
                            <div class="btns" @click="searchClick('detail')">
                                <a-icon class="btns-icon" type="file-search" />
                                <div class="btns-text">查询</div>
                            </div>
                        </a-col>

                        <a-col :xs="2" :sm="2" :md="2" :lg="2" :xl="2">
                            <div class="btns" style="display:block;margin-left:10px">
                                <a class="ant-dropdown-link" @click="printClick">
                                    <a-icon class="btns-icon" type="printer" />
                                    <div class="btns-text">打印</div>
                                </a>
                            </div>
                        </a-col>
                    </a-col>
                </a-row>

            </div>
            <div ref="print" class="documents-wrapper" id="documents-wrapper">
                <h3 class="text-center">工序汇报明细</h3>

                <section v-show="showModel=='detail'">
                    <!--明细-->
                    <dynamicListDetails v-if="showTabel" @checkChange="checkChange" :checkedBox="checkedBoxType" :getListType.sync="getListType" :createdShow="true" ref="detailSearchRef" :reportCode="reportCodeDetail" :componentType="1" :basePostData="basePostData"></dynamicListDetails>
                </section>
            </div>
            <div class="contextmenu-box">
                <!-- 右键菜单 -->
                <ul v-show="visibleX" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
                    <li @click="handleAdd()">新增行</li>
                    <li @click="handleDelete()">删除行</li>
                    <!-- <li @click="handleCopy()">复制行</li> -->
                </ul>
            </div>
            <drawerBox ref="searchList" :unitData="unitData" :unitsData="unitsData" :unitsDataDetails="unitsDataDetails" @editClickOrder="editClickOrder"></drawerBox>
        </div>

        <!--加载中-->
        <div class="loading-wrapper" v-show="loading">
            <a-spin class="loading-content" tip="加载中..." />
        </div>
        <!--用做横向打印-->
        <!-- <div v-html="stylePrint"></div> -->
        <print-modal ref="printDom" v-if="printVisible" :incomingPrintData="incomingPrintData" @cancelPrint="cancelPrint"></print-modal>

        <!--选加工单-->
        <!--全局组件可拖动弹窗-->
        <drag-modal title="新建工序汇报" :visible="visibleProcessing" centered width="1100px" @cancel="()=>{visibleProcessing = false}">
            <template>
                <p>选择加工产品</p>
                <div style="min-height: 230px;">
                    <a-table v-if="visibleProcessing" :rowClassName="rowClassName" :scroll="{ x: 1000, y: 200 }" :columns="columnModal1" :data-source="modalList1" :customRow="tableChange1" bordered :pagination="false" :loading="tableShowLoding"></a-table>
                </div>
                <div class="titleDiv">
                    <div>汇报日期:{{dayDate}}</div>
                    <div class="title">工序汇报</div>
                </div>
                <div class="table-box-mmp" style="min-height: 230px;">
                    <a-table :scroll="{ x: 1000, y: 200 }" :columns="columnModal2" :data-source="modalList2" bordered :customRow="tableChange2" :row-selection="rowSelection" :pagination="false">
                        <template v-for="col in slotArry" :slot="col" slot-scope="text, record, index">
                            <div data-key="">
                                <editableCells v-if="isRouterAlive" :dynamicAllData="timeSlotArr" :showTotal="false" :text="text" :col="col" :index="index" :record="record" @change="onCellChange(index, col, $event)" :dataSource="modalList2" />
                            </div>
                        </template>
                    </a-table>
                </div>
            </template>
            <template slot="footer">
                <div>
                    <a-button type="primary" @click="addClick">提交</a-button>
                    <a-button @click="cancel()" class="margin-left-10">关闭</a-button>
                </div>
            </template>
            <div class="contextmenu-box" ref="contextmenuBox">
                <!-- 右键菜单 -->
                <ul v-show="visible" class="contextmenu">
                    <li @click="handleDelete()">删除行</li>
                </ul>
            </div>
        </drag-modal>

        <!--修改弹窗-->
        <drag-modal title="修改工序汇报" :visible="xgVisible" centered width="1100px" @cancel="()=>{xgVisible = false}">
            <div class="table-box-mmp" style="min-height: 230px;">
                <a-table :scroll="{ x: 1000, y: 200 }" :columns="xgColumn" :data-source="xgModalList" bordered :customRow="tableChange2" :pagination="false">
                    <template v-for="col in slotXgArry" :slot="col" slot-scope="text, record, index">
                        <div data-key="">
                            <editableCells v-if="isRouterAlive" :dynamicAllData="timeSlotArr" :showTotal="false" :text="text" :col="col" :index="index" :record="record" @change="onCellChange(index, col, $event)" :dataSource="xgModalList" />
                        </div>
                    </template>
                </a-table>
            </div>

            <template slot="footer">
                <div>
                    <a-button type="primary" @click="preservationClick">保存</a-button>
                    <a-button @click="()=>{xgVisible = false}" class="margin-left-10">关闭</a-button>
                </div>
            </template>
            
        </drag-modal>

          
    </div>
</template>
<script>
import { save, examine, remove, getCode } from '@/api/sale/quotation'
import pro from '@/mixins/procurement/pro';
import searchArchives from "@/components/OrderDynamicForm/searchArchives";
import FormSearchGroup from '@/components/Form/FormSearchGroup';
import {
    listUnFinishProcedureDetailDispatchVo,
    getUnFinishProductionWorkVo,
    createCardDetail,
    batchSaveCardDetail,
    batchDelete,
    batchExamine,
    listByIds
} from '@/api/production/productionProcessReport'
import editableCells from "@/components/OrderDynamicForm/EditableCell";
import { mapState } from "vuex";
export default {
    mixins: [pro],
    data () {
        const columnModal1 = [
            {
                title: "生产车间",
                dataIndex: "officeName",
                align: 'center',
                width: 80
            },
            {
                title: "加工单号",
                dataIndex: "productionWorkCode",
                align: 'center',
                width: 80
            },
            // {
            //   title: "物料编码",
            //   dataIndex: "inventoryCode",
            //   align: 'center',
            //   scopedSlots: {
            //     customRender: "inventoryCode",
            //   },
            // },
            {
                title: "物料名称",
                dataIndex: "inventoryName",
                align: 'center',
                width: 80,
                scopedSlots: {
                    customRender: "inventoryName",
                },
            },
            {
                title: "规格型号",
                dataIndex: "inventorySpecification",
                align: 'center',
                width: 80,
                scopedSlots: {
                    customRender: "inventorySpecification",
                },
            },
            {
                title: "生产数量",
                dataIndex: "baseQuantity",
                align: 'center',
                width: 80,
                scopedSlots: {
                    customRender: "baseQuantity",
                },
            },
            {
                title: "完成数量",
                dataIndex: "cumExecuteQuantity",
                align: 'center',
                width: 80,
                scopedSlots: {
                    customRender: "cumExecuteQuantity",
                },
            },
            {
                title: "预计完工时间",
                dataIndex: "expectFinishDate",
                align: 'center',
                width: 80,
                scopedSlots: {
                    customRender: "expectFinishDate",
                },
            },

        ];

        const columnModal2 = [
            // {
            //   title: "派工单号",
            //   dataIndex: "productionDispatchCode",
            //   align: 'center',
            // },
            // {
            //     title: "工人姓名",
            //     dataIndex: "workerName",
            //     align: 'center',
            //     width: 80,
            //     fixed: 'left',
            // },
            {
                title: "工序名称",
                dataIndex: "procedureName",
                align: 'center',
                width: 80,
                fixed: 'left',
            },
            //  {
            //     title: "班组",
            //     dataIndex: "teamName",
            //     align: 'center',
            //     width: 80,
            // },
            // {
            //     title: "生产车间",
            //     dataIndex: "officeName",
            //     align: 'center',
            //     width: 80,
            // },
            {
                title: "工序标识",
                dataIndex: "workFlag",
                align: 'center',
                width: 80,
                customRender: (text, row, index) => {
                  switch(text){
                    case 1: return "首工序";
                    case 2: return "尾工序";
                    case 3: return "中间工序"
                  }
                }
            },
            {
                title: "生产设备",
                dataIndex: "equipmentName",
                align: 'center',
                width: 80,
            },
            {
                title: "累计合格数量",
                dataIndex: "cumQualifiedQuantity",
                align: 'center',
                width: 100,
            },
             {
                title: "累计返工数量",
                dataIndex: "cumReworkQuantity",
                align: 'center',
                width: 100,
            },
            {
                title: "累计不合格数量",
                dataIndex: "cumUnqualifiedQuantity",
                align: 'center',
                width: 100,
            },
            {
                title: "累计报废数量",
                dataIndex: "cumScrapQuantity",
                align: 'center',
                width: 100,
            },
            {
                title: "累计提交数量",
                dataIndex: "totalReport",
                align: 'center',
                width: 100,
                customRender: (text, row, index) => {
                    let { cumQualifiedQuantity, cumUnqualifiedQuantity, cumReworkQuantity } = row;
                    if (isNaN(cumQualifiedQuantity) || isNaN(cumUnqualifiedQuantity) || isNaN(cumReworkQuantity)) {
                        return false;
                    }
                    return cumQualifiedQuantity + cumUnqualifiedQuantity + cumReworkQuantity;
                }
            },
            {
                title: "合格数量",
                dataIndex: "qualifiedQuantity",
                align: 'center',
                width: 80,
                Required: true,
                scopedSlots: {
                    customRender: "qualifiedQuantity",
                }
            },
            {
                title: "返工数量",
                dataIndex: "reworkQuantity",
                align: 'center',
                width: 80,
                Required: true,
                scopedSlots: {
                    customRender: "reworkQuantity",
                }
            },
            {
                title: "不合格数量",
                dataIndex: "unqualifiedQuantity",
                align: 'center',
                width: 80,
                Required: true,
                scopedSlots: {
                    customRender: "unqualifiedQuantity",
                }
            },
            {
                title: "报废数量",
                dataIndex: "scrapQuantity",
                align: 'center',
                width: 80,
                Required: true,
                scopedSlots: {
                    customRender: "scrapQuantity",
                }
            },
            {
                title: "状态",
                dataIndex: "status",
                align: 'center',
                width: 80,
                customRender: (text, row, index) => {
                    let { status } = row;
                    if (status == 0) {
                        return '加工中'
                    } else if (status == 10) {
                        return '完工'
                    }
                }
            },
            {
                title: "加工日期",
                dataIndex: "workDate",
                align: 'center',
                width: 100,
                scopedSlots: {
                    customRender: "workDate",
                }
            },
            {
                title: "加工开始时间",
                dataIndex: "workBeginTime",
                align: 'center',
                width: 100,
                scopedSlots: {
                    customRender: "workBeginTime",
                }
            },
            {
                title: "加工结束时间",
                dataIndex: "workEndTime",
                align: 'center',
                width: 100,
                scopedSlots: {
                    customRender: "workEndTime",
                }
            },
            {
                title: "报废原因",
                dataIndex: "unqualifiedReason",
                align: 'center',
                width: 120,
                scopedSlots: {
                    customRender: "unqualifiedReason",
                }
            },
        ];
        const slotArry = ['qualifiedQuantity', 'unqualifiedQuantity','reworkQuantity', 'scrapQuantity', , 'workDate', 'workEndTime', 'workBeginTime','unqualifiedReason']

        const xgColumn = [
            {
                title: "汇报单号",
                dataIndex: "reportCode",
                align: 'center',
                width: 80
            },
            {
                title: "工人姓名",
                dataIndex: "workerName",
                align: 'center',
                width: 80,
            },
            {
                title: <div><span style="color:red">*</span>合格数量</div>,
                dataIndex: "qualifiedQuantity",
                align: 'center',
                width: 80,
                Required: true,
                scopedSlots: {
                    customRender: "qualifiedQuantity",
                }
            },
            {
                title: <div><span style="color:red">*</span>返工数量</div>,
                dataIndex: "reworkQuantity",
                align: 'center',
                width: 80,
                Required: true,
                scopedSlots: {
                    customRender: "reworkQuantity",
                }
            },
            {
                title: <div><span style="color:red">*</span>报废数量</div>,
                dataIndex: "scrapQuantity",
                align: 'center',
                width: 80,
                Required: true,
                scopedSlots: {
                    customRender: "scrapQuantity",
                }
            },
            {
                title: "加工日期",
                dataIndex: "workDate",
                align: 'center',
                width: 80,
                scopedSlots: {
                    customRender: "workDate",
                }
            },
            {
                title: "加工开始时间",
                dataIndex: "workBeginTime",
                align: 'center',
                width: 80,
                scopedSlots: {
                    customRender: "workBeginTime",
                }
            },
            {
                title: "加工结束时间",
                dataIndex: "workEndTime",
                align: 'center',
                width: 80,
                scopedSlots: {
                    customRender: "workEndTime",
                }
            }
        ];
        const slotXgArry = ['qualifiedQuantity', 'reworkQuantity', 'scrapQuantity', 'workDate', 'workBeginTime', 'workEndTime'];

        return {
            //基础 查询条件（列表 + 翻页）
            basePostData: {
                someBusinessType: null,
            },
            slotXgArry,
            xgVisible: false,//修改弹窗
            xgColumn,//修改表头
            xgModalList: [],//修改数据
            showTabel: true,
            tableArrIds: [],
            bcType: false,//保存按钮状态
            xgType: false,//修改按钮状态
            scType: false,//删除按钮状态
            shType: false,//审核按钮状态
            qsType: false,//弃审按钮状态
            getListType: false,//是否从新拉拉取数据
            checkedBoxType: true,//是否需要复选框功能
            isRouterAlive: true,
            slotArry,
            timeSlotArr: [
                { code: 'workDate', columnType: '日期', onEdit: true },
                { code: 'workEndTime', columnType: '时间', onEdit: true },
                { code: 'workBeginTime', columnType: '时间', onEdit: true },
            ],
            visible: false,
            top: 0,
            left: 0,
            grid2: {
                xs: 24,
                sm: 24,
                md: 12,
                lg: 8,
                xl: 8,
                xxl: 8,
            },
            grid: {
                xs: 24,
                sm: 24,
                md: 12,
                lg: 8,
                xl: 8,
                xxl: 8,
            },
            labelCol: {
                span: 10,
            },
            wrapperCol: {
                span: 14,
            },
            open1: false,
            open2: false,
            pgSource1: {},
            hbSource1: {
                code: null,//汇报编号
                hbDate: null,//汇报日期
                jgStarTime: null,//加工开始时间
                jgStarTime1: null,
                jgEndTime: null,//加工结束时间
                jgEndTime1: null,
                jgTime: null,//加工用时 
                newjgtime: null,//传的加工用时
                serialNumber: null,//序列号
                qualifiedQuantity: null,//合格数量
                reworkQuantity: null,//返工数量
                scrapQuantity: null,//报废数量
                // reasonsForScrapping: null,//报废原因
                unqualifiedReason:null,//报废原因
                batchNumber: null,//生产批号
            },
            dayDate: "",
            columnModal1,
            modalList1: [],
            columnModal2,
            modalList2: [],
            JsonList2: [],
            inventoryDomTop: null,
            maskArchives: false,
            showModalType: 0,
            visibleProcessing: false,
            showModel: 'detail',
            sourceCode: 'SaleQuotation',
            reportCodeDetail: 'ReportProcedure_Detail_Report',
            // reportCodeStatistical: 'SaleQuotation_Statistic_Report',   //统计code   
            thisClickNoEndId: null,
            grid2: {
                xs: 24,
                sm: 24,
                md: 12,
                lg: 8,
                xl: 8,
                xxl: 8,
            },
            thisClickId: null,
            searchData: {
                expectStartDateEnd: null,// 预计开工日期_结束
                expectStartDateStart: null,// 预计开工日期_开始
                inventoryName: null,//产品名称
                inventoryId: null,// 物料id（产品ID）
                officeId: null,// 生产车间id
                officeName: null,//生产车间名称
                productionWorkCode: null,// 加工单号
                saleOrderCode: null,// 销售单号
                voucherCode: null,// 单据编号(派工单号)
                voucherDateEnd: null,// 单据日期_结束
                voucherDateStart: null,// 单据日期_开始
            },
            selectedRowKeys1: [],   //选择的加工产品Keys  
            selectedDetailRow:[],   //选择的加工产品    
            selectedKeys:[],        //选择需要汇报的工序的key
            selectedRows:[],        //选择需要汇报的工序记录
            checkType: null,//物料类型 1:采购 2:销售 3:生产（bom）
        };
    },
    computed: {
        ...mapState({
            userInfo: state => state.user.info,
            permissions: state => state.user.permissions,
        }),
         rowSelection () {
            return {
                selectedRowKeys: this.selectedKeys,
                onChange: this.onSelectChange,
            }
        }
    },
    components: {
        searchArchives,
        FormSearchGroup,
        editableCells,
    },

    watch: {
        visible (value) {
            if (value) {
                document.body.addEventListener("click", () => this.visible = false);
            } else {
                document.body.removeEventListener("click", () => this.visible = false);
            }
        }
    },

    created () {
        // this.getIdByData();//获取最新一条数据
        var nowDate = new Date();
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1)
            : nowDate.getMonth() + 1;
        var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
        this.dayDate = year + "-" + month + "-" + day;

        //jsX
        this.columnModal2.forEach(item => {
            if (item.Required) {
                let title = <div><span style="color:red;font-family: SimSun,sans-serif;font-size:14px">*</span>{item.title}</div>
                item.title = title;
            }
        })
       
    },
    mounted(){
        this.$refs.detailSearchRef.getMyselfPlan();
    },
    methods: {
         onSelectChange (keys, rows) {
            this.selectedKeys = keys;
            this.selectedRows = rows;
        },
        printClick () {
            this.$print(this.$refs.print);
        },
        //修改时， 保存工序
        preservationClick () {
            for (let index = 0; index < this.xgModalList.length; index++) {
                const items = this.xgModalList[index];
                if (items.qualifiedQuantity === '' || items.qualifiedQuantity == undefined) {
                    this.$message.warning('请填写合格数量');
                    return;
                };
                if (items.reworkQuantity === '' || items.reworkQuantity == undefined) {
                    this.$message.warning('请填写返工数量');
                    return;
                };
                if (items.scrapQuantity === '' || items.scrapQuantity == undefined) {
                    this.$message.warning('请填写报废数量');
                    return;
                };
                if ((items.workBeginTime || items.workEndTime) && !items.workDate) {
                    this.$message.warning('必须选择“加工日期”后才能选择“加工时间”');
                    return;
                }

                //等于2才验证
                if (items.wagesType == 2) {
                    if (!items.workDate) {
                        this.$message.warning('请选择加工日期');
                        return;
                    };
                    if (!items.workBeginTime) {
                        this.$message.warning('请选择加工开始时间');
                        return;
                    };
                    if (!items.workEndTime) {
                        this.$message.warning('请选择加工结束时间');
                        return;
                    };
                }
                items.qualifiedQuantity = Number(items.qualifiedQuantity) || 0; // 合格数量
                items.reworkQuantity = Number(items.reworkQuantity) || 0; //返工数量
                items.unqualifiedQuantity = Number(items.unqualifiedQuantity) || 0;//（不合格数量）
                items.scrapQuantity = Number(items.scrapQuantity) || 0;//（报废数量）
                // 为2才有工时
                if (items.wagesType == 2) {
                    if (items.workBeginTime && items.workEndTime) {
                        if (items.workBeginTime.indexOf('-') == -1) {
                            let arr1 = items.workBeginTime.split(":");
                            let time1 = Number(arr1[0]) * 60 + Number(arr1[1]);
                            let arr2 = items.workEndTime.split(":");
                            let time2 = Number(arr2[0]) * 60 + Number(arr2[1]);
                            let minutes = time2 - time1;
                            let h = Math.floor(minutes / 60);
                            let m = minutes % 60;
                            let h1 = m / 60;
                            items.workHour = h + h1;
                            items.workBeginTime = items.workDate + " " + items.workBeginTime || ''; //开始
                            items.workEndTime = items.workDate + " " + items.workEndTime || ''; //结束
                        }

                    }
                }
            }

            let requestData = _.cloneDeep(this.xgModalList);
            requestData.forEach(item => {
                if (item.wagesType != 2) {
                    if (item.workBeginTime) {
                        item.workBeginTime = item.workDate + ' ' + item.workBeginTime;
                    }
                    if (item.workEndTime) {
                        item.workEndTime = item.workDate + ' ' + item.workEndTime;
                    }
                }
            });

            batchSaveCardDetail(requestData).then(res => {
                if (res.code === 200) {
                    this.$message.success('保存成功');
                    this.xgVisible = false;
                    //从新拉取数据
                    this.getListType = true;
                }
            })
        },

        // 1.审核   2.弃审
        shClick (type) {
            //只有为0 的才可以审核  只有为1的才可以弃审
            if (this.tableArrIds.length == 0) {
                this.$message.warning("至少选择一条数据");
                return;
            }
            let arr = [];
            for (let index = 0; index < this.tableArrIds.length; index++) {
                const item = this.tableArrIds[index];
                if (type == 1) {
                    if (item.wpcd_status != 0) {
                        this.$message.warning(`汇报单号为：${item.wpcd_reportCode}已审核,不能再次审核`);
                        return;
                    }
                } else if (type == 2) {
                    console.log('>', type)
                    if (item.wpcd_status != 1) {
                        this.$message.warning(`汇报单号为：${item.wpcd_reportCode}未审核,不能弃审核`);
                        return;
                    }
                }
                arr.push(item.id);
            }
            let obj = { ids: arr, status: type == 1 ? 1 : 0 }//0弃审 ，1审核
            batchExamine(obj).then(res => {
                //从新拉取数据
                this.getListType = true;
                this.tableArrIds = [];
                if (type == 1) this.$message.success('审核成功');
                if (type == 2) this.$message.success('弃审成功');
                //强制刷新表格
                this.showTabel = false;
                this.$nextTick(function () {
                    this.showTabel = true;
                });
            })
        },

        //删除2 修改1
        deleteClick (type) {
            //wpcd_status 0 未审核  1.已审核  2.已核算
            //只有为0 的才可以删除或修改
            if (this.tableArrIds.length == 0) {
                this.$message.warning("至少选择一条数据");
                return;
            }
            let arr = [];
            for (let index = 0; index < this.tableArrIds.length; index++) {
                const item = this.tableArrIds[index];
                if (item.wpcd_status != 0) {
                    this.$message.warning(`汇报单号为：${item.wpcd_reportCode}已审核,不能${type == 1 ? '修改' : '删除'}`);
                    return;
                }
                arr.push(item.id);
            }
            //修改
            if (type == 1) {
                listByIds(arr).then(res => {
                    if (res.code == 200) {
                        res.data.forEach(item => {
                            if (item.workBeginTime) {
                                let sIndex = item.workBeginTime.indexOf(' ');
                                item.workBeginTime = item.workBeginTime.substring(sIndex + 1);
                            }
                            if (item.workEndTime) {
                                let eIndex = item.workEndTime.indexOf(' ');
                                item.workEndTime = item.workEndTime.substring(eIndex + 1);
                            }
                            item.tableType = 'xgVisible';//修改表格专属字段
                        });
                        // res.data.forEach(item => {
                        //     //报废数量置入值
                        //     item.scrapQuantity = item.unqualifiedQuantity
                        // });

                        this.xgModalList = res.data;
                        this.$nextTick(() => {
                            this.newTable();
                            this.xgVisible = true;
                        });
                    }
                })
            } else {
                //删除
                batchDelete(arr).then(res => {
                    if (res.code == 200) {
                        //从新拉取数据
                        this.getListType = true;
                        this.tableArrIds = [];
                        this.$message.success('删除成功');
                        //强制刷新表格
                        this.showTabel = false;
                        this.$nextTick(function () {
                            this.showTabel = true;
                        });
                    }
                })
            }
        },

        checkChange (e) {
            this.tableArrIds = e;
        },

        //表格修改赋值
        onCellChange (indexTable, dataIndex, value) {
            //先判断表格
            console.log(indexTable, dataIndex, value)
            let dataSource;
            if (value instanceof Object && 'tableType' in value) {
                //在修改表格操作
                dataSource = [...this.xgModalList];
            } else {
                //在新增表格操作
                dataSource = [...this.modalList2];
            }
            const target = dataSource.find((item, index) => index === indexTable);

            console.log(target)
            //区分表格
            if (value instanceof Object && 'tableType' in value) {
                if (dataIndex == 'qualifiedQuantity') {
                    target['qualifiedQuantity'] = value.value;
                } 
                if (dataIndex == 'unqualifiedQuantity') {
                    target['unqualifiedQuantity'] = value.value;
                } else if (dataIndex == 'reworkQuantity') {
                    target['reworkQuantity'] = value.value;
                } else if (dataIndex == 'scrapQuantity') {
                    target['scrapQuantity'] = value.value;
                } else if (dataIndex == 'workEndTime') {
                    target['workEndTime'] = value.value;
                } else if (dataIndex == 'workBeginTime') {
                    target['workBeginTime'] = value.value;
                } else if (dataIndex == 'workDate') {
                    target['workDate'] = value.value;
                }else if (dataIndex == 'unqualifiedReason') {
                    target['unqualifiedReason'] = value.value;
                }
                target[dataIndex] = value.value;
                this.$nextTick(() => {
                    this.newTable();
                });
                return;
            }


            if (dataIndex == 'workBeginTime') {
                target['workBeginTime'] = value.value;
            } else if (dataIndex == 'qualifiedQuantity') {
                target['qualifiedQuantity'] = value;
            }else if (dataIndex == 'unqualifiedQuantity') {
                target['unqualifiedQuantity'] = value;
            }  else if (dataIndex == 'reworkQuantity') {
                target['reworkQuantity'] = value;
            } else if (dataIndex == 'scrapQuantity') {
                target['scrapQuantity'] = value;
            } else if (dataIndex == 'workDate') {
                target['workDate'] = value.value;
            } else if (dataIndex == 'workEndTime') {
                target['workEndTime'] = value.value;
            }else if (dataIndex == 'unqualifiedReason') {
                target['unqualifiedReason'] = value;
            }
            this.$nextTick(() => {
                this.newTable();
            });

        },

        newTable () {
            //刷新表格
            this.isRouterAlive = false;
            this.$nextTick(function () {
                this.isRouterAlive = true;
            });
        },


        handleAdd () {
            //新增数据
            const newData = {};
            this.$nextTick(() => {
                this.modalList2.splice(this.modalList2.length, 0, newData);
            });
            console.log("新增行：", this.modalList2);
        },
        handleDelete () {
            //删除整行
            let _this = this;
            let numberId = this.thisClickId;
            let modalList2 = JSON.parse(JSON.stringify(_this.modalList2));
            _this.modalList2 = modalList2.filter(
                (item, index) => index !== numberId
            );
        },



      

        //派工明细表格点击
        dispatchChange (record, index) {
            return {
                on: {
                    contextmenu: (e) => {
                        //右键事件
                        e.preventDefault();
                        console.log("右键点击的", index,e);
                       
                        // if (index <= this.dataSource.length) {
                        this.openMenu(e);
                        //   console.log("右键点击的", index);
                        this.thisClickId = index;
                        //   // this.thisClickRecord = record;
                        // }
                    },
                },
            };
        },

        openMenu (e) {
            //显示右键菜单
            // var x = (e.pageX + e.layerX)/2;
            // var y = e.clientY;
            // this.top = y;
            // this.left = x;
            this.visible = true;
        },

        onChange1 (e, s, i) {
            if (!this.hbSource1.hbDate) {
                this.hbSource1.jgStarTime1 = "";
                this.$set(this.hbSource1, 'jgStarTime', '');
                this.hbSource1.jgEndTime1 = "";
                this.$set(this.hbSource1, 'jgEndTime1', '');
                this.$message.warning("请先选择汇报日期");
                return;
            }

            if (i == 1) {
                this.hbSource1.jgStarTime1 = s;
            } else {
                this.hbSource1.jgEndTime1 = s;
            }
            if (this.hbSource1.jgStarTime1 && this.hbSource1.jgEndTime1) {
                let arr1 = this.hbSource1.jgStarTime1.split(":");
                let time1 = Number(arr1[0]) * 60 + Number(arr1[1]);
                let arr2 = this.hbSource1.jgEndTime1.split(":");
                let time2 = Number(arr2[0]) * 60 + Number(arr2[1]);
                let minutes = time2 - time1;
                let h = Math.floor(minutes / 60);
                let m = minutes % 60;
                let h1 = m / 60;
                this.hbSource1.jgTime = Math.floor(minutes / 60) + "时" + (minutes % 60) + "分"
                this.hbSource1.newjgtime = h + h1;
            }
        },



        onChangeDate (v, s, index) {
            if (index == 1) {
                this.hbSource1.hbDate = s;
            }
        },

        hideClick () {
            this.showModalType = 0;
            this.maskArchives = false;
        },
        //提交 工序汇报
        addClick () {
          const { selectedKeys ,selectedRows } = this;
          console.log('选择的工序',selectedRows)
            //提交
            if (this.selectedDetailRow.length == 0) {
                this.$message.warning('请选择加工产品');
                return;
            }
            if (selectedKeys.length == 0) {
                this.$message.warning('请选择汇报的工序记录');
                return;
            }
            if (selectedRows.length > 0) {
                try {
                    selectedRows.forEach(item=>{
                    const {qualifiedQuantity,reworkQuantity,unqualifiedQuantity,scrapQuantity} = item;
                    if( !qualifiedQuantity && !reworkQuantity && !unqualifiedQuantity && !scrapQuantity){
                        throw new Error('请填写汇报数量');
                    }
                    if ((item.workBeginTime || item.workEndTime) && !item.workDate) {
                        throw new Error('必须选择“加工日期”后才能选择“加工时间”');
                    }
                    //等于2才验证
                    if (item.wagesType == 2) {
                        if (!item.workDate) {
                            throw new Error('请选择加工日期');
                        };
                        if (!item.workBeginTime) {
                            throw new Error('请选择加工开始时间');
                        };
                        if (!item.workEndTime) {
                            throw new Error('请选择加工结束时间');
                        };
                    }
                });
                } catch (error) {
                    this.$message.warning(error.message);
                    return;
                }
                
            } else {
                this.$message.warning('抱歉没有工序不能提交');
                return;
            }

            //组装数据
            selectedRows.forEach(obj => {
                obj.inventoryId = this.selectedDetailRow.inventoryId; //产品ID
                obj.procedureId = obj.procedureId;//工序id
                obj.procedureName = obj.procedureName;//工序名称
                obj.productionWorkMainId = obj.productionWorkMainId;//加工单ID
                obj.productionWorkDetailId = obj.productionWorkDetailId;//加工单明细ID
                obj.productionWorkProcedureDetailId = obj.productionWorkProcedureDetailId;
                obj.teamId = obj.teamId;//班组id
                obj.teamName = obj.teamName;//班组名称
                obj.workerId = obj.workerId;//工人ID
                obj.workerName = obj.workerName;//工人姓名
                // 为2才有工时
                if (obj.wagesType == 2) {
                    if (obj.workBeginTime && obj.workEndTime) {
                        if (obj.workBeginTime.indexOf('-') == -1) {
                            let arr1 = obj.workBeginTime.split(":");
                            let time1 = Number(arr1[0]) * 60 + Number(arr1[1]);
                            let arr2 = obj.workEndTime.split(":");
                            let time2 = Number(arr2[0]) * 60 + Number(arr2[1]);
                            let minutes = time2 - time1;
                            let h = Math.floor(minutes / 60);
                            let m = minutes % 60;
                            let h1 = m / 60;
                            obj.workHour = h + h1;
                            obj.workBeginTime = obj.workDate + " " + obj.workBeginTime || ''; //开始
                            obj.workEndTime = obj.workDate + " " + obj.workEndTime || ''; //结束
                        }

                    }
                }
                obj.qualifiedQuantity = Number(obj.qualifiedQuantity) || 0; // 合格数量
                obj.reworkQuantity = Number(obj.reworkQuantity) || 0; //返工数量
                obj.unqualifiedQuantity = Number(obj.unqualifiedQuantity) || 0;//（不合格数量）
                obj.scrapQuantity = Number(obj.scrapQuantity) || 0;//（报废数量）
            });
            selectedRows.forEach(item => {
                if (item.wagesType != 2) {
                    if (item.workBeginTime) {
                        item.workBeginTime = item.workDate + ' ' + item.workBeginTime;
                    }
                    if (item.workEndTime) {
                        item.workEndTime = item.workDate + ' ' + item.workEndTime;
                    }
                }
            });
            batchSaveCardDetail(selectedRows).then(res => {
                if (res.code == 200) {
                    this.$message.success('保存成功');

                    //清空数据
                    this.JsonList2 = [];
                    this.modalList1 = [];
                    this.modalList2 = [];
                    this.selectedDetailRow = [];
                    this.selectedRowKeys1 = [];
                    this.visibleProcessing = false;
                    //强制刷新表格
                    this.showTabel = false;
                    this.$nextTick(function () {
                        this.showTabel = true;
                    });
                    this.getListType = true;
                }
            })
        },
        rowClassName (record, index) {
            return this.thisClickNoEndId == record.id ? "hoverRowCard" : "";
        },

        //弹窗搜索
        searchBillsWork () {
            this.getList();
        },
        //加工单明细表 表格点击监听
        tableChange1 (record, index) {
            return {
                on: {
                    click: () => {
                        console.log("加工单明细表",record, index, this.JsonList2)
                        let keys = [];
                        this.thisClickNoEndId = record.id;
                        keys.push(index);
                        this.selectedRowKeys1 = keys;
                        this.selectedDetailRow = record;


                        let arr = [];
                        this.JsonList2.forEach(item => {
                            if (record.id == item.productionWorkDetailId) {
                                arr.push(item);
                            }
                        });
                        console.log("modalList2--->>",arr);
                        if (arr.length > 0) {
                            this.modalList2 = arr;
                        } else {
                            this.modalList2 = [];
                        }
                        this.selectedKeys = [];
                        this.selectedRows = [];
                    }
                }
            }
        },
        //表格点击监听
        tableChange2 (record, index) {
            return {
                on: {
                    contextmenu: (e) => {
                        console.log("工序汇报明细 右键点击",e);
                        console.log("e.target.classList：",e.target.classList);
                        let isHave = e.target.classList.contains("ant-table-row-cell-break-word");
                        if(!isHave){
                            e.target.parentNode.parentNode.parentNode.appendChild(this.$refs.contextmenuBox);
                        }else{
                            e.target.appendChild(this.$refs.contextmenuBox);
                        }
                        //右键事件
                        e.preventDefault();
                        this.openMenu(e);
                        this.thisClickId = index;
                    },
                }
            }
        },

        //根据数据权限 获取未完工 的派工任务
        getList (type) {
            let obj = {
                expectStartDateEnd: this.searchData.expectStartDateEnd,
                expectStartDateStart: this.searchData.expectStartDateStart,
                inventoryId: this.searchData.inventoryId,
                officeId: this.searchData.officeId,
                productionWorkCode: this.searchData.productionWorkCode,
                saleOrderCode: this.searchData.saleOrderCode,
                voucherCode: this.searchData.voucherCode,
                voucherDateEnd: this.searchData.voucherDateEnd,
                voucherDateStart: this.searchData.voucherDateStart,
            };
            getUnFinishProductionWorkVo(obj).then(res => {
                
                if (res.code == 200) {
                    console.log("获取数据:",res);
                    //表格1
                    if (res.data.unFinishProductionWorkDetailSimpleVoList.length > 3) {
                        this.modalList1 = res.data.unFinishProductionWorkDetailSimpleVoList;
                    } else {
                        res.data.unFinishProductionWorkDetailSimpleVoList.forEach((item, index) => {
                            this.modalList1[index] = item;
                        })
                    }
                    //需要用到该数据遍历
                    this.JsonList2 = JSON.parse(JSON.stringify(res.data.unFinishProductionWorkProcedureVoList));
                    //清空key
                    this.selectedRowKeys1 = [];
                    this.selectedDetailRow = [];
                    this.visibleProcessing = true;
                    if (type == 1) {
                        let w = document.body.clientWidth; //当前可视窗口宽度
                        if (w < 1600) {
                            this.inventoryDomTop = 240;
                        } else {
                            this.inventoryDomTop = 195;
                        }
                    }
                }
            });
            // 废弃 20220101 白强
            // listUnFinishProcedureDetailDispatchVo(obj).then(res => {
            //     if (res.code == 200) {
            //         //表格1
            //         if (res.data.productionDispatchSimpleVoList.length > 3) {
            //             this.modalList1 = res.data.productionDispatchSimpleVoList;
            //         } else {
            //             res.data.productionDispatchSimpleVoList.forEach((item, index) => {
            //                 this.modalList1[index] = item;
            //             })
            //         }
            //         //需要用到该数据遍历
            //         this.JsonList2 = JSON.parse(JSON.stringify(res.data.procedureDetailSimpleVoList));
            //         //清空key
            //         this.selectedRowKeys1 = [];
            //         this.visibleProcessing = true;
            //         if (type == 1) {
            //             let w = document.body.clientWidth; //当前可视窗口宽度
            //             if (w < 1600) {
            //                 this.inventoryDomTop = 240;
            //             } else {
            //                 this.inventoryDomTop = 195;
            //             }
            //         }
            //     }
            // });
        },

        setValueTips (data) {
            if (data.codesName == 'office') {
                this.searchData.officeId = data.id;
                this.searchData.officeName = data.name;
            }
        },

        handleSearch1 (n) {
            this.$refs[`${n}`].showModal();
        },

        checkArchives (data) {
            this.searchData.inventoryId = data[0][0].inventoryCode;
            this.searchData.inventoryName = data[0][0].inventoryName;
            this.maskArchives = false;
        },

        cancel () {
            this.visibleProcessing = false;
        },

        ok () {
            this.visibleProcessing = false;
        },

        handlInputArchives (num) {
            this.showModalType = num;
            this.maskArchives = true;
            console.log(num)
        },

        closeArchives () {
            this.showModalType = 0;
            this.maskArchives = false;
        },



        showModelsClick () {
            //打开之前清空数据
            this.selectedRowKeys1 = [];
            this.selectedDetailRow = [];
            this.thisClickNoEndId = null;
            this.searchData = {
                expectStartDateEnd: null,// 预计开工日期_结束
                expectStartDateStart: null,// 预计开工日期_开始
                inventoryName: null,//产品名称
                inventoryId: null,// 物料id（产品ID）
                officeId: null,// 生产车间id
                officeName: null,//生产车间名称
                productionWorkCode: null,// 加工单号
                saleOrderCode: null,// 销售单号
                voucherCode: null,// 单据编号(派工单号)
                voucherDateEnd: null,// 单据日期_结束
                voucherDateStart: null,// 单据日期_开始
            };
            this.modalList1 = [];
            this.modalList2 = [];
            this.showModalType = 0;
            this.maskArchives = false;
            //发送请求
            this.getList(1);
        },

        onChangeDate1 (e, v, type) {
            if (type == 1) {
                this.searchData.expectStartDateStart = v[0];
                this.searchData.expectStartDateEnd = v[1];
            } else {
                this.searchData.voucherDateStart = v[0];
                this.searchData.voucherDateEnd = v[1];
            }
        },


        exportDetail (e) {
            console.log(11, e)
        },
        //新增预测单
        newForecast () {
            this.editMask = false;
            this.loading = false;
            this.voucherState = -1;
            this.sourceVoucherData = {};//清空来源数据
            this.initForm(1);
        },
        //保存
        submit (requestData) {
            save(requestData).then(response => {
                if (response.code === 200) {
                    this.$message.success('保存成功');
                    this.editMask = true;
                    this.isSaveRun = true;
                    if (!this.orderId) {
                        this.getIdByData(); //获取最新一条数据
                    }
                } else {
                    this.$message.error(response.message);
                    this.isSaveRun = true;
                }
            }).catch((e) => {
                this.isSaveRun = true;
            })
        },
        //审核
        auditClick (type) {
            let requestData = {
                id: this.orderId,
                status: type
            }
            examine(requestData).then((response) => {
                if (response.code === 200) {
                    const backData = response.data;
                    if (type == 1) {
                        this.$message.success('审核成功');
                        this.getIdByData();
                    }
                    if (type == 0) {
                        this.$message.success('弃审成功');
                        this.getIdByData();
                    }
                } else {
                    // this.$message.warning(response.message);
                }
            })
        },
        //删除
        remove (postData) {
            remove(postData).then(response => {
                if (response.code === 200) {
                    this.$message.success('删除成功');
                    this.orderId = '';
                    this.voucherState = 0;
                    this.getIdByData();//获取最新一条数据
                } else {
                    this.$message.error(response.message);
                }
            })
        },
        //获取单据编号
        getCode () {
            getCode().then((res) => {
                if (res.code == 200) {
                    console.log(res);
                    this.receiptNumber = res.message;
                    console.log(this.orderHeaderData)
                    for (let i = 0; i < this.orderHeaderData.length; i++) {
                        if (this.orderHeaderData[i].code == 'voucherCode') {
                            this.$set(this.orderHeaderData[i], 'onEdit', false)
                            this.$set(this.orderHeaderData[i], 'value', this.receiptNumber)
                        }
                    }
                } else {
                    // this.$message.warning(res.message);
                }
            });
        },
        

    }
};
</script>
<style lang="less">
    @import '~@/style/purchase/voucher.less';
    .models {
        width: 100%;
        height: 100%;
        position: absolute;
        z-index: 1111;
        top: 0px;
        left: 0px;
    }
    .titles {
        width: 100%;
        text-align: center;
        font-size: 20px;
        font-weight: bold;
    }
    .titleDiv {
        display: flex;
        flex-direction: row;
        position: relative;
        margin-bottom: 15px;
        .title {
            position: absolute;
            top: 50%;
            left: 50%;
            z-index: 1;
            transform: translate(-50%, -50%);
            font-size: 18px;
            font-weight: bold;
        }
    }

    //右键
    .contextmenu-box {
        .contextmenu {
            margin: 0;
            background: #fff;
            z-index: 3000;
            position: absolute;
            list-style-type: none;
            padding: 5px 0;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 400;
            color: #333;
            position: absolute;
            box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
        }

        .contextmenu li {
            margin: 0;
            padding: 7px 16px;
            cursor: pointer;
        }

        .contextmenu li:hover {
            background: #eee;
        }
    }
    .hoverRowCard {
        background-color: rgba(24, 144, 255, 0.2);
        td {
            color: #222;
        }
    }

    .table-box-mmp {
        .editable-cell-input-wrapper {
            .ant-input {
                border: 1px solid #000;
                border-radius: 0px;
            }
        }
    }
</style>